import { IsNotEmpty, IsString, IsArray, IsOptional, IsNumber } from 'class-validator';
import { UserResponseDto } from './user.dto';

export class CreateArticleDto {
  @IsNotEmpty({ message: '标题不能为空' })
  @IsString()
  title: string;

  @IsNotEmpty({ message: '内容不能为空' })
  @IsString()
  content: string;

  @IsOptional()
  @IsString()
  coverImage?: string;

  @IsOptional()
  @IsNumber({}, { message: '状态必须是数字' })
  isActive?: number;

  @IsArray({ message: '标签ID必须是数组格式' })
  @IsNumber({}, { each: true, message: '每个标签必须是数字ID' })
  tagIds: number[];
}

export class UpdateArticleDto {
  @IsOptional()
  @IsString()
  title?: string;

  @IsOptional()
  @IsString()
  content?: string;

  @IsOptional()
  @IsString()
  coverImage?: string;

  @IsOptional()
  @IsNumber({}, { message: '状态必须是数字' })
  isActive?: number;

  @IsOptional()
  @IsArray({ message: '标签ID必须是数组格式' })
  @IsNumber({}, { each: true, message: '每个标签必须是数字ID' })
  tagIds?: number[];
}

export class ArticleResponseDto {
  id: number;
  title: string;
  content: string;
  coverImage: string;
  viewCount: number;
  likeCount: number;
  categoryId: number;
  isActive: number;
  tags: Array<{ id: number; name: string }>;
  createdAt: Date;
  updatedAt: Date;
  author: {
    id: number;
    username: string;
    avatar: string;
    email: string;
  };

  constructor(article: any, user : UserResponseDto) {
    this.id = article.id;
    this.title = article.title;
    this.content = article.content;
    this.coverImage = article.coverImage || '';
    this.viewCount = article.viewCount || 0;
    this.likeCount = article.likeCount || 0;
    this.categoryId = article.categoryId || 0;
    this.isActive = article.isActive !== undefined ? article.isActive : -1;
    this.tags = article.tags ? article.tags.map((tag: any) => ({
      id: tag.id,
      name: tag.name
    })) : [];
    this.createdAt = article.createdAt;
    this.updatedAt = article.updatedAt;
    this.author = article.authorId ? {
      id: user.id || 0,
      username:  user.username || '',
      avatar: user.avatar || '',
      email: user.email || '',
    } : { id: 0, username: '', avatar: '' , email: '' };
  }
}